package cn.diaomin.servlet;

import cn.diaomin.entity.Working;
import cn.diaomin.service.WorkingService;
import cn.diaomin.service.impl.WorkingServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "ServletWorking",urlPatterns = "/working")
public class ServletWorking extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        WorkingService ws=new WorkingServiceImpl();
        String opr=request.getParameter("opr");
        if(opr==null){
            List<Working> workings=ws.getAll();
            request.setAttribute("workingList",workings);
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }else if(opr.equals("getCount")){
            String title=request.getParameter("title");
            int count=ws.getCount(title);
            PrintWriter out=response.getWriter();
            if(count>0){
                out.print("true");
            }
            out.flush();
            out.close();
        }else if(opr.equals("add")){
            Working working=new Working(
                    request.getParameter("title"),
                    request.getParameter("content"),
                    Integer.parseInt(request.getParameter("type"))
            );
            int rs=ws.add(working);
            PrintWriter out=response.getWriter();
            if(rs>0){
                out.print("true");
            }
            out.flush();
            out.close();
        }else if(opr.equals("getOne")){
            String id=request.getParameter("id");
            Working working=ws.getOne(Integer.parseInt(id));
            request.setAttribute("working",working);
            request.getRequestDispatcher("/working_show.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
